import React, {useState} from 'react';
import {Alert, Image, ScrollView, StyleSheet, Text, View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {StatusBar} from 'expo-status-bar';
import AppHeader from '../components/AppHeader';
import PrimaryButton from '../components/PrimaryButton';
import UploadField from '../components/UploadField';
import InputField from '../components/InputField';
import {Colors} from '../constants/colors';
import {useNavigation} from '@react-navigation/native';
import {merchantService} from '../services';

export default function MerchantRegisterScreen() {
	const [form, setForm] = useState({
		name: '',
		businessName: '',
		tel: '',
		credentials: '',
		credentialsFiles: '',
		businessLicense: '',
		businessLicenseFiles: '',
		certificateFiles: '',
		remark: '',
	});
	const [loading, setLoading] = useState(false);

	const set = (k: keyof typeof form, v: string) => setForm(prev => ({...prev, [k]: v}));
	const nav = useNavigation<any>();

	// 验证表单
	const validateForm = () => {
		if (!form.name.trim()) {
			Alert.alert('錯誤', '請輸入商家姓名');
			return false;
		}
		if (!form.businessName.trim()) {
			Alert.alert('錯誤', '請輸入商家名稱');
			return false;
		}
		if (!form.tel.trim()) {
			Alert.alert('錯誤', '請輸入聯絡電話');
			return false;
		}
		if (!form.credentials.trim()) {
			Alert.alert('錯誤', '請輸入身份證號碼');
			return false;
		}
		if (!form.businessLicense.trim()) {
			Alert.alert('錯誤', '請輸入營業執照號碼');
			return false;
		}
		return true;
	};


	// 处理注册
	const handleRegister = async () => {
		if (!validateForm()) {
			return;
		}

		setLoading(true);
		try {
			const result = await merchantService.addMerchant({
				name: form.name.trim(),
				businessName: form.businessName.trim(),
				tel: form.tel.trim(),
				credentials: form.credentials.trim(),
				credentialsFiles: form.credentialsFiles,
				businessLicense: form.businessLicense.trim(),
				businessLicenseFiles: form.businessLicenseFiles,
				certificateFiles: form.certificateFiles,
				remark: form.remark.trim(),
			});

			Alert.alert('註冊成功', result.message || '商家註冊申請已提交，請等待審核', [
				{
					text: '確定',
					onPress: () => nav.reset({
						index: 0,
						routes: [{name: 'MainTabs', params: {initialTab: 'Profile'}}],
					}),
				},
			]);
		} catch (error: any) {
			console.error('商家注册失败:', error);
			Alert.alert('註冊失敗', error.message || '註冊過程中發生錯誤，請稍後重試');
		} finally {
			setLoading(false);
		}
	};
	return (
		<SafeAreaView style={styles.container}>
			<StatusBar style="light" backgroundColor="#f97316"/>
			<AppHeader title="商家註冊" showBack variant="plain"/>

			<ScrollView 
				style={styles.content} 
				contentContainerStyle={styles.contentInner}
				showsVerticalScrollIndicator={false}
				nestedScrollEnabled={true}
				scrollEnabled={true}
				bounces={false}
				overScrollMode="never"
			>
				<View style={styles.heroRow}>
					<View>
						<Text style={styles.heroTitle}>成為商家</Text>
						<Text style={styles.heroSub}>添加導師更好管理</Text>
					</View>
					<Image
						source={{uri: 'https://images.unsplash.com/photo-1517963879433-6ad2b056d712?q=80&w=200&auto=format&fit=crop'}}
						style={{width: 72, height: 72, borderRadius: 36}}/>
				</View>

				{/* Inputs - card style */}
				<View style={{marginBottom: 12}}>
					<InputField
						label="商家姓名 *"
						value={form.name}
						onChangeText={(v) => set('name', v)}
						placeholder="請輸入商家姓名"
						variant="card"
					/>
				</View>
				<View style={{marginBottom: 12}}>
					<InputField
						label="商家名稱 *"
						value={form.businessName}
						onChangeText={(v) => set('businessName', v)}
						placeholder="請輸入商家名稱"
						variant="card"
					/>
				</View>
				<View style={{marginBottom: 12}}>
					<InputField
						label="聯絡電話 *"
						value={form.tel}
						onChangeText={(v) => set('tel', v)}
						placeholder="請輸入聯絡電話"
						keyboardType="phone-pad"
						variant="card"
					/>
				</View>
				<View style={{marginBottom: 12}}>
					<InputField
						label="身份證號碼 *"
						value={form.credentials}
						onChangeText={(v) => set('credentials', v)}
						placeholder="請輸入身份證號碼"
						variant="card"
					/>
				</View>
				<View style={{marginBottom: 12}}>
					<InputField
						label="營業執照號碼 *"
						value={form.businessLicense}
						onChangeText={(v) => set('businessLicense', v)}
						placeholder="請輸入營業執照號碼"
						variant="card"
					/>
				</View>
				<View style={{marginBottom: 12}}>
					<InputField
						label="備註"
						value={form.remark}
						onChangeText={(v) => set('remark', v)}
						placeholder="請輸入備註信息（可選）"
						variant="card"
						multiline
					/>
				</View>

				<View style={{marginBottom: 12}}>
					<UploadField
						label="身份證照片 *"
						uri={form.credentialsFiles}
						onUploadComplete={(ossUrl) => set('credentialsFiles', ossUrl)}
						tipText="上傳身份證照片"
					/>
				</View>
				<View style={{marginBottom: 12}}>
					<UploadField
						label="營業執照照片 *"
						uri={form.businessLicenseFiles}
						onUploadComplete={(ossUrl) => set('businessLicenseFiles', ossUrl)}
						tipText="上傳營業執照照片"
					/>
				</View>
				<View style={{marginBottom: 12}}>
					<UploadField
						label="其他證書"
						uri={form.certificateFiles}
						onUploadComplete={(ossUrl) => set('certificateFiles', ossUrl)}
						tipText="上傳其他相關證書（可選）"
					/>
				</View>

				<PrimaryButton
					title={loading ? "註冊中..." : "立即註冊"}
					onPress={handleRegister}
					disabled={loading}
					style={{marginTop: 12}}
				/>
			</ScrollView>
		</SafeAreaView>
	);
}

const styles = StyleSheet.create({
	container: {flex: 1, backgroundColor: Colors.white},
	content: {
		flex: 1,
		height: '100%',
	},
	contentInner: {
		flexGrow: 1,
		padding: 20,
		paddingBottom: 40,
		minHeight: '100%',
	},

	heroRow: {flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16},
	heroTitle: {fontSize: 24, fontWeight: '800', color: Colors.black},
	heroSub: {color: Colors.gray[400], marginTop: 6},

	card: {
		backgroundColor: Colors.white,
		borderRadius: 16,
		paddingHorizontal: 16,
		paddingVertical: 14,
		marginBottom: 12,
		borderWidth: 1,
		borderColor: Colors.gray[200],
		shadowColor: Colors.black,
		shadowOpacity: 0.05,
		shadowRadius: 6,
		shadowOffset: {width: 0, height: 2},
		elevation: 1,
	},

	input: {height: 24, color: Colors.black},
	placeholderText: {color: Colors.gray[400]},
	inputRow: {height: 24},
});

